package com.boboPlanet.dict.consume;

import com.alibaba.fastjson.JSON;
import com.boboPlanet.comm.entity.dto.PlanetMqMsg;
import com.boboPlanet.comm.entity.po.FileDetailPO;
import com.boboPlanet.comm.rabbitmq.consume.PlanetConsumeListener;
import com.boboPlanet.dict.service.PlanetFileService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @Description: TODO保存文件MQ
 * @Author: mis_wu
 * @Date: 2023/7/11
 * @Company planet
 **/
@Slf4j
@Component
public class PlanetSaveFileConsume implements PlanetConsumeListener{

    @Override
    public String queue() {
        return null;
    }

    @Override
    public String exchange() {
        return null;
    }

    @Override
    public String routingKey() {
        return null;
    }

    @Override
    public String ackMode() {
        return null;
    }

    @Resource
    private PlanetFileService planetFileService;

    /**
     * received 'direct' but current is 'topic' ==> 交换机不加type默认direct
     */
    @RabbitListener(bindings = {@QueueBinding(value = @Queue("planet.saveFile.queue"),
    exchange = @Exchange(value = "planet.saveFile.topic",type = ExchangeTypes.TOPIC),key = "planet.saveFile")},ackMode = "MANUAL")
    public void receive(@NotNull Message message, Channel channel, long tag) throws IOException {
        String dataStr = new String(message.getBody());
        PlanetMqMsg mqData = PlanetMqMsg.deserialize(dataStr);

        FileDetailPO detail = JSON.parseObject((String) mqData.getData(),FileDetailPO.class);
        if (detail == null){
            log.error("save file mq is empty,param: {},msgData:{}",dataStr,mqData);
            return;
        }
        try {
            FileDetailPO fileById = planetFileService.getFileById(detail.getId());
            if (fileById == null){
                Boolean file = planetFileService.saveFile(detail);
                log.info("save planet file mq, detail is: {},result is:{}",detail,file);
            }else {
                log.warn("save planet file mq,file exist,not save, the fileId is: {}",detail.getId());
            }
            //手动确认
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            // 手动拒绝消息
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
            //todo 重新发送消息到队尾
            log.error("save file rabbitmq consume fail,reason: {}",e.getMessage(),e);
        }
    }
}
